package com.qf.common.core.event;

import org.slf4j.MDC;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.GenericApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.ResolvableType;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.util.StringUtils;

public class MyLogApplicationListener implements GenericApplicationListener {

    /**
     * 判断当前的监听器 具体要监听的事件类型
     * @return
     */
    @Override
    public boolean supportsEventType(ResolvableType eventType) {
        return ApplicationEnvironmentPreparedEvent.class.isAssignableFrom(eventType.getRawClass());
    }

    @Override
    public boolean supportsSourceType(Class<?> sourceType) {
        return true;
    }


    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        //转换成环境的事件对象
        ApplicationEnvironmentPreparedEvent environmentPreparedEvent = (ApplicationEnvironmentPreparedEvent) event;

        //获取当前的环境信息
        ConfigurableEnvironment environment = environmentPreparedEvent.getEnvironment();
        MutablePropertySources propertySources = environment.getPropertySources();
        PropertySource<?> propertySource = propertySources.get("configurationProperties");
        //获取微服务的配置文件中 应用的名称
        String serverName = (String) propertySource.getProperty("spring.application.name");
        String logName = (String) propertySource.getProperty("logging.file.name");
        String logPath = (String) propertySource.getProperty("logging.file.path");
        //封装到MDC容器中
        MDC.put("appName", StringUtils.isEmpty(logName) ? serverName : logName);
        MDC.put("appPath", StringUtils.isEmpty(logPath) ? serverName : logPath);
    }

    /**
     * 事件监听器的排序方法 - 返回的值越小优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 19;
    }
}
